<?php
namespace PsiFramework\Applications\AlloMediaUser\Classes\Actions;

import("Applications.AlloMediaPortal.Classes.Actions.AlloMediaUserAction");
import("Applications.AlloMediaPortal.Classes.Model.InformationPart");
import("Classes.Util.HTTP.AuthenticationManager");
import("Classes.Factory.DAOFactory");
import("Plugins.Form.Classes.DAO.FormResponseDAO");
import("Plugins.Form.Classes.Model.FormResponse");
import("Classes.Util.Object.File");
import("Classes.Util.Object.Image");

use \PsiFramework\Applications\AlloMediaPortal\Classes\Actions\AlloMediaUserAction;
use \PsiFramework\Applications\AlloMediaPortal\Classes\Model\InformationPart;
use \PsiFramework\Classes\Exceptions\SecurityException;
use \PsiFramework\Classes\Util\HTTP\AuthenticationManager;
use \PsiFramework\Classes\Util\Object\Date;
use \PsiFramework\Classes\Util\Parameters\Action\ActionParameters;
use \PsiFramework\Classes\Factory\DAOFactory;
use \PsiFramework\Plugins\Form\Classes\DAO\FormResponseDAO;
use \PsiFramework\Plugins\Form\Classes\Model\FormResponse;
use \PsiFramework\Classes\Util\Object\File;
use \PsiFramework\Classes\Util\Object\Image;
use \PsiFramework\Plugins\Form\Classes\Util\Json\Elements\JsonFormInput;
use \PsiFramework\Classes\Util\HTTP\HTTPRequest;
use \PsiFramework\Classes\Util\HTTP\Request;
use \PsiFramework\Classes\Util\Manager\ApplicationManager;
use \PsiFramework\Applications\AlloMediaPortal\Classes\DAO\AlloMediaEntryDAO;


/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 * Classe d'action de l'index
 *
 * @package Actions.Pages
 */
class AlloMediaSaveProfile extends AlloMediaUserAction
{

    /**
     * Constructor
     * 
     * @param ActionParameters $actionParameters The action parameters
     * 
     * @return AlloMediaSaveProfile
     */
    public function __construct(ActionParameters $actionParameters)
    {
        parent::__construct($actionParameters);
    }

    /**
     * The main function of the method which is called every time
     * an action is created by the front controller.
     *
     * @return void
     */
    public function execute()
    {
        parent::execute();

        $formId = $this->_request->getParameter('form_id');
        $form = null ;

        $entry = null;
        
        if ($formId == 'entry') {
            $entry = $this->_response->getAttribute('entry');
            $entry->setAddress($this->_request->getParameter('address'));
            $entry->setCity($this->_request->getParameter('city'));
            $entry->setZip($this->_request->getParameter('zip'));
            
            $entry->setFax($this->_request->getParameter('fax'));
            $entry->setMobile($this->_request->getParameter('mobile'));
            $entry->setTel2($this->_request->getParameter('tel2'));
            
            $entry->setModificationDate(Date::now());

            $entryDao = DAOFactory::getDAO('AlloMediaEntry');
            $entryDao->save($entry);
        } else if (!isNullOrEmptyString($formId) && is_numeric($formId)) {
            $formDao = DAOFactory::getDAO('Form');
            $form = $formDao->retrieveByPk($formId);
            
            if (is_null($form)) {
                throw new Exception("Impossible to retrieve the theme !");
            }
            
            $responseIdDao = DAOFactory::getDAO('ResponseId');
            $responseId
                = $responseIdDao->retrieveByPk(
                    $this->_request->getParameter('id')
                );
            
            $categoryDao = DAOFactory::getDAO('SiteCategory');
            $category = $categoryDao->retrieveByPk($this->_request->getParameter('category_id'));
            
            $samplePart = new InformationPart();
            $samplePart->setTheme($form);
            $samplePart->setProfile($category->getprofile());
            $informationPartDao = DAOFactory::getDAO('InformationPart');
            $part = $informationPartDao->retrieveByPk($samplePart->getId());
            
            if (!is_null($responseId) && ($responseId->isActive() || $part->isFree())) {
                
                $entry = $responseId->getEntry();
                
                $responseParameters = $form->getResponseParameters();
                $jsonForm = $form->getStructure();
                
                $formResponseDao
                    = FormResponseDAO::getInstance($responseParameters);
    
                $formResponse = null ;
    
                $previous = $this->_request->getParameter('previous');
                if (!isNullOrEmptyString($previous)) {
                    $formResponse = $formResponseDao->retrieveByPk($previous);
                    
                    if (is_null($formResponse) || (!is_null($formResponse->getUser()) && $formResponse->getUser()->getId()!=$this->_user->getId())) {
                    	throw new SecurityException(
                			'You can\'t save these information !'
                    	);
                    }
                    
                } else {
                    $formResponse = $formResponseDao->retrieveByPk($this->_request->getParameter('id'));
                    
                    if (is_null($formResponse)) {
                        $formResponse = new FormResponse();
                    } else if (!is_null($formResponse->getUser()) && $formResponse->getUser()->getId()!=$this->_user->getId()) {
                        throw new SecurityException(
                			'You can\'t save these information !'
                    	);
                    }
                        
                    foreach ($jsonForm->getElements() as $field) {
                        foreach ($field->getElements() as $element) {
                            if ($element instanceof JsonFormInput) {
                                $param = $responseParameters->getParameter($element->getName());
                                
                                $paramName = $param->name ;
                                if ($paramName != 'id' && $paramName != 'user') {
                                    $val = null ;
                                    if ($param->type == 'File' || $param->type == 'Image') {
                                        $val = $this->_request->getFile($paramName);
                                        if (is_null($val)) {
                                            $delete = $this->_request->getParameter('delete_'.$paramName);
                                            if (isNullOrEmptyString($delete)) {
                                                $val = $this->_request->getParameter('current_'.$paramName);
                                            } else {
                                                unlink($delete);
                                            }
                                        }
                                    } else {
                                        $val = $this->_request->getParameter($paramName);
                                        if (isNullOrEmptyString($val)) {
                                            $val = null;
                                        }
                                    }
                                    
                                    $value = null ;
                                    if (is_array($val)) {
                                        foreach ($val as $v) {
                                            if ($value != '') {
                                                $value .= ',' ;
                                            }
                                            $value .= $v ;
                                        }
                                    } else if (!is_null($val)) {
                                        if ($param->type == 'Date') {
                                            $val = Date::getDateFromFrenchString($val);
                                        } else if ($val instanceof File) {
                                            $fileName = uniqid().'.'.$val->getExtension();
                                            $filePath = realpath('./Images/Upload');
                                            $val->setName($fileName);
                                            $val->moveTo($filePath);
                                            
                                            if ($param->type == 'Image'
                                                && !is_null($element->getImageWidth())
                                                && !is_null($element->getImageHeight())
                                            ) {
                                                $newPath = $filePath.'/resized_'.$fileName;
                                                $val = new Image($val);
                                                $val->createResizedPictures(
                                                    $newPath,
                                                    $element->getImageWidth(),
                                                    $element->getImageHeight()
                                                );
                                                if (file_exists($newPath)) {
                                                    $file = new File();
                                                    $file->unserialize($newPath);
                                                    $val = new Image($file);
                                                } else {
                                                    $val = null;
                                                }
                                            }
                                        } else if ($param->type == 'File' || $param->type == 'Image') {
                                            $file = new File();
                                            $file->unserialize($val);
                                            
                                            if ($param->type == 'Image') {
                                            	$val = new Image($file);
                                            } else {
                                                $val = $file ;
                                            }
                                        }
                                        
                                        $value = $val ;
                                    }
                                    
                                    $formResponse->{$param->setter}($value);
                                }
                            }
                        }
                    }
                }
    
                $formResponse->setId($this->_request->getParameter('id'));
                $formResponse->setUser($this->_response->getAttribute('user'));
                
                $formResponseDao->save($formResponse);
            }

        } else {
            throw new SecurityException('Impossible to save!');
        }
        
        if (!is_null($entry)) {
            
            $password = ApplicationManager::getInstance()->getApplication()->getParameter('xmlPassword');
            $updateUrl =  ApplicationManager::getInstance()->getApplication()->getParameter('updateUrl');
            
            $doc = new \DOMDocument('1.0', 'UTF-8');
            $doc->formatOutput = true;
            $entryXml = AlloMediaEntryDAO::getAsXml($entry, null, $doc);
            $doc->appendChild($entryXml);
            
            $sites = $entry->getSites();
            foreach ($sites as $siteMembership) {
                $idForSite = $siteMembership->getSiteUserId();
                $site = $siteMembership->getSite();
                
                $entryXml->setAttribute("id", $idForSite);
                
                $entryXmlString = $doc->saveXML();
                $this->_logger->debug($entryXmlString);
                
                $httpRequest
                    = new HTTPRequest(
                		$site->getUri().$updateUrl
                    );
                $httpRequest->addParameter('information', $entryXmlString);
                $httpRequest->addParameter('securityKey', sha1($entryXmlString.$password));
                
                try {
                    $response = $httpRequest->execute(HTTPRequest::$post);
                    $this->_logger->debug('Updating entry for '.$site->getUri().' : '.$response);
                } catch (\Exception $e) {
                    $this->_logger->debug('Updating entry for '.$site->getUri().' : Impossible to send the Request to update the entry : ' . $e->getMessage());
                }
            }
        }
        
        $this->findForward("success");
    }
}
